import type { VideoDanmaku } from 'usuuu'

/**
 * 获取弹幕类型
 * 
 * @param key 弹幕类型
 */
export const getMode = (key: number) => {
    switch (key) {
    case 1:
    case 2:
    case 3:
        return 0
    case 4:
    case 5:
        return 1
    default:
        return 0
    }
}
/**
 * 解析弹幕xml
 * 
 * @param xmlString XML数据
 */
export const bilibiliDanmuParseFromXml = (xmlString: string) => {
    if (typeof xmlString !== 'string') return []
    const matches = xmlString.matchAll(/<d (?:.*? )??p="(?<p>.+?)"(?: .*?)?>(?<text>.+?)<\/d>/gs)
    return Array.from(matches)
        .map((match: any) => {
            const attr = match.groups.p.split(',')
            if (attr.length >= 8) {
                const text = match.groups.text
                    .trim()
                    .replaceAll('&quot;', '"')
                    .replaceAll('&apos;', '\'')
                    .replaceAll('&lt;', '<')
                    .replaceAll('&gt;', '>')
                    .replaceAll('&amp;', '&')
                return {
                    text,
                    time: Math.floor(Number(attr[0])),
                    mode: getMode(Number(attr[1])),
                    fontSize: `${Number(attr[2])}px`,
                    color: `#${Number(attr[3]).toString(16)}`,
                    timestamp: Number(attr[4]),
                    pool: Number(attr[5]),
                    userID: attr[6],
                    rowID: Number(attr[7])
                }
            } else {
                return null
            }
        })
        .filter(Boolean)
}
/**
 * 弹幕XML链接
 * 
 * @param url XML弹幕链接
 */
export const bilibiliDanmuParseUrl = async (url: RequestInfo | URL) => {
    const res = await fetch(url)
    const xmlString = await res.text()
    const resultArray = bilibiliDanmuParseFromXml(xmlString) as unknown as VideoDanmaku[]
    return resultArray
}